from helloweb.templating import render as template_render
from michiren.model import dai
from helloweb import htmls
from helloweb import app_context
import simplejson as json
class BaseController:
    def __call__(self, environ, start_response):
        
        self.__setup__(environ, start_response)
        
        req_context = environ['helloweb.reqctx']
        method = req_context.method
        args   = req_context.args
        method = getattr(self, method)
        
        res = method(*args)
        if type(res) != str:
            res = json.dumps(res)
        req_context.output.append(res)
    def __setup__(self, environ, start_response):
        self.environ = environ
        self.start_response = start_response
        
        req_context = environ['helloweb.reqctx']
        self.req_context = req_context
        self.d = req_context.render_context
        self.get_params = req_context.get_params
        self.post_params = req_context.post_params
        self.cookie = req_context.cookie
        self.session = req_context.session
        
    def transmit(self, ctrname, method, *kw):
        clsname = ctrname.capitalize()
        cls = __import__("controller." + ctrname, globals(), locals(), [clsname])
        cls = getattr(cls, clsname)
        ctr = cls()
        ctr.__setup__(self.environ, self.start_response)
        method = getattr(ctr, 'index')
        return method(*kw)
    
    def render(self, file):
        filename = 'module/%s/template/%s'%(self.modulename, file)
        print filename
        return self._render(filename)
    
    def _render(self, filename):
        args = {'d':self.d,
                'lib':app_context.lib,
                'req_context':self.req_context,
                'cookie': self.cookie,
                'session':self.session,
                'dai':dai,
                'html':htmls}
        return template_render(filename, args)